package io.github.talelin.latticy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.latticy.mapper.CommentMapper;
import io.github.talelin.latticy.mapper.CommentReplyMapper;
import io.github.talelin.latticy.model.ArticleDO;
import io.github.talelin.latticy.model.CommentDO;
import io.github.talelin.latticy.model.CommentReplyDO;
import io.github.talelin.latticy.model.SpuDO;
import io.github.talelin.latticy.mapper.SpuMapper;
import io.github.talelin.latticy.service.SpuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.talelin.latticy.vo.ArticleVO;
import io.github.talelin.latticy.vo.SpuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author generator@lms
 * @since 2021-04-27
 */
@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, SpuDO> implements SpuService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private CommentReplyMapper commentReplyMapper;

    @Override
    public SpuVO getSpu(Integer id) {
         SpuDO spu = this.getById(id);
         if (spu == null) {
             throw new NotFoundException(80400);
         }
        //获取该文章下的一级评论
        List<CommentDO> comments = commentMapper.selectList(new QueryWrapper<CommentDO>()
                .eq("article_id", id)
                .eq("type",1)
                .orderByAsc("create_time"));
        comments.forEach(c -> {
            //获取一级评论下所有的回复
            List<CommentReplyDO> commentReplyList = commentReplyMapper.selectList(new QueryWrapper<CommentReplyDO>()
                    .eq("comment_id", c.getId())
                    .orderByAsc("create_time"));
            c.setReplyList(commentReplyList);
        });
        return SpuVO.builder()
                .spu(spu)
                .comments(comments)
                .commentCount(comments.size())
                .build();
    }

    @Override
    public void checkSpu(Integer id, Integer online) {
        SpuDO spu = this.getById(id);
        if (spu == null) {
            throw new NotFoundException(80400);
        }
        spu.setOnline(online);
        this.updateById(spu);
    }
}
